/**英语学籍照片导出 */
<template>
  <div class="student-regist-container">
    <!-- <div style="height: 30px;">
      <el-breadcrumb style="float: left;" separator="/">
        <el-breadcrumb-item :to="{ path: '/putonghuaExamsCreate' }">
        <span @click="reback()">{{ $t('mandarin.createExams') }}</span></el-breadcrumb-item>
        <el-breadcrumb-item>{{ $t('mandarin.stuRegistStatistics') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
    </div> -->
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{$t('cetStatistics.studentExported')}}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-left">
          <el-input
            v-model.trim="queryForm.condition.student"
            :placeholder="$t('subjectCompetitionBase.studentIdOrName')"
            style="width:250px"
            @keyup.enter.native="onSubmit">
              <i slot="suffix"
                class="el-icon-search"
                style="margin-top:10px;cursor:pointer"
                @click="onSubmit">
              </i>
          </el-input>
          
        </div>
        <div class="float-left" v-if="dataList.length!=0" :class="{'color':taskStatus==1||taskStatus==2?color:colors}" style="margin-left:50px;margin-top:8px">{{taskMsg}}</div>
        <div class="float-right" style="display: flex;">
          <el-button type="primary" @click="importAuditRosterClick">{{$t('englishScoreManage.lead')}}</el-button>
          <el-button type="primary" @click="stopLead">{{ $t('englishScoreManage.stopLead') }}</el-button>
          <el-button type="primary" @click="exportTemplate">{{$t('englishScoreManage.template')}}</el-button>
          <el-button v-if="zipUrl" type="primary" @click="exportAuditRoster">{{$t('cetStatistics.exportPhotos')}}</el-button>
          <el-dialog
            :title="$t('englishScoreManage.lead')"
            :visible.sync="listRmportVisible"
            width="30%"
            :close-on-click-modal='false'
            :before-close="cancelRmport">
            <el-form ref="queryFormRmport" :rules="rulesRmport" :model="queryFormRmport" label-width="80px">
                <el-form-item :label="$t('englishScoreManage.lead')" prop="enclosureFileName">
                  <el-upload
                    class="upload-demo"
                    v-model="queryFormRmport.enclosureFileName"
                    action=""
                    :http-request='changeRequest'
                    :headers="{'X-Token': $store.state.session.sessionid}"
                    :data="{bucketname: 'face', folderpath: 'file'}"
                    :on-change="handleChange"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    :auto-upload='false'
                    :limit="1"
                    ref='uploadLead'
                    :file-list="fileList">
                    <el-button size="small" type="primary">{{$t('englishScoreManage.selectFile')}}</el-button>
                    <div slot="tip" class="el-upload__tip">{{$t('requirement.attachment')}}</div>
                  </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancelRmport">{{$t('studentsRegist.cancel')}}</el-button>
              <el-button type="primary" @click="reliableRmport">{{$t('englishScoreManage.confirm')}}</el-button>
            </span>
          </el-dialog>
          <!-- <el-upload style="display: none;"
            class="upload-demo"
            :auto-upload="false"
            action="api/competitionservice/cet/importStudent"
            :headers="{'X-Token': $store.state.session.sessionid}"
            :data="{bucketname: 'face', folderpath: 'file',educationTag: Number(this.$store.getters.getProjectId())}"
            :limit="1"
            accept='.xlsx,.xls'
            ref='uploadLead'
            :on-progress='handleChange'
            :on-success="handleSuccess"
            :file-list="fileList"
            >
            <span slot="trigger" ref="selectFile">{{$t('internship.selectFile')}}</span>
          </el-upload> -->
        </div>
      </div>
      <edu-table :pagination="false" :tooltipEffect="tooltipEffect" :selection='false' stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
        <edu-table-column :label="$t('subjectCompetitionBase.name')" prop="studentName"></edu-table-column>
        <edu-table-column :label="$t('subjectCompetitionBase.studentId')" prop="studentId"></edu-table-column>
        <edu-table-column :label="$t('subjectCompetitionBase.college')" prop="collegeAcademyI18n"></edu-table-column>
        <edu-table-column :label="$t('computational.major')" prop="majorI18n"></edu-table-column>
      </edu-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
  </div>
</template>
<script>
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import graduateStudent from 'common/src/api/graduateStudent/graduateStudent';
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
export default {
  props: {
    examId: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: {
  },
  data () {
    return {
      taskMsg: '',
      taskStatus: '',
      formList: new FormData(),
      queryFormRmport: {
        enclosureFileName: ''
      },
      rulesRmport: {
        enclosureFileName: [
          { required: true, message: this.$t('internship.attachment'), trigger: 'change' } 
        ]
      },
      auths: [],
      fileList: [],
      zipUrl: false,
      listRmportVisible: false,
      permitToImport: true,
      permitToExport: true,
      importAuditRoster: false,
      multipleSelection: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          student: '',
          educationTag: Number(this.$store.getters.getProjectId())
        }
      },
      loadList: [],
      semesterRmpor: [],
      options: {
        college: [],
        status: [
          {
            label: '已报名',
            value: 1
          },
          {
            label: '待报名',
            value: 0
          },
          {
            label: '报名成功',
            value: 2
          },
          {
            label: '无资格',
            value: 3
          }
        ]
      },
      zipUrlList: '',
      calendarName: '',
      useConfigParamList: '',
      useConfigParam: '',
      dataList: [],
      exportButton: false,
      exportResult: null
    }
  },
  filters: {
    status(val) {
      switch (val) {
        case 0:
          return '已报名'
        case 1:
          return '报名结束'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    // this.getSchoolCalendar()
    this.getListData()
    // this.getOptions()
    // console.log(this.$store.getters.getGlobal().isUndergraduate, 'this.isUndergraduate');
    // console.log(this.$store.getters.getGlobal(), 'this.getGlobal');
    // console.log(Number(this.$store.getters.getProjectId()), 'this.getProjectId');  // 获取本研在职
    
  },
  methods: {
    // 终止导入
    stopLead() {
      subjectCompetitionApi.stopImport().then(res => {
        this.$message.success(this.$t('course.operateSuccess'));
        this.getListData();
      })
    },
    getSchoolCalendar() {
      graduateStudent.schoolCalendar().then(res => {
        this.semesterRmpor = res.data;
        this.semesterRmpor.forEach(el => {
          if (el.fullName=== this.examId.calendarYearTerm) {
            this.queryForm.condition.calendarId = el.id;
          }
        });
      }).then(() => {
        this.getListData()
      });
    },
    
    // // 上传成功
    // handleSuccess(res, file, fileList) {
    //   let isSuccess = (res.code == 200);
    //   // console.log(res, file, fileList);
    //   if(res.code!=200) {
    //     this.fileList = [];
    //     this.$message({
    //       type: isSuccess ? "success":"error",
    //       message: res.msg
    //     });
    //   } else {
    //     this.$message({
    //       type: isSuccess ? "success":"error",
    //       message: res.msg
    //     });
    //     // this.$message(res.msg);
    //     // this.$message.success(this.$t('studentsRegist.successfully'));
    //     this.fileList = []
    //     this.queryForm.pageNum_ = 1;
    //     this.getListData();
    //   }
    // },
    // 导入取消
    cancelRmport() {
      this.$refs['queryFormRmport'].resetFields();
      this.fileList = [];
      // console.log(this.queryFormRmport);
      this.formList = new FormData();
      this.queryFormRmport.enclosureFileName = '';
      this.listRmportVisible = false;
    },
    // 上传之前
    handleChange(file) {
      if (!file.name.endsWith(".xlsx") && !file.name.endsWith(".xls")){
        this.fileList = [];
        this.formList = new FormData();
        return this.$message.warning(this.$t('cetStatistics.formatError'))
      }
      this.queryFormRmport.enclosureFileName = 'a';
    },
    // 删除
    handleRemove() {
      this.queryFormRmport.enclosureFileName = '';
      this.formList = new FormData();
      this.fileList = [];
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
      // console.log(res, file, fileList, '1212');
      
      let isSuccess = (res.code == 200);
      this.$message({
          type: isSuccess ? "success":"error",
          message: res.msg
      });
      // this.setInformationAttachList(fileList);
    },
    setInformationAttachList(fileList) {
      let attachList = [];
      fileList.forEach(item => {
        if (item.response && item.response.data) {
          const uploadedObj = item.response.data[item.name];
          if (uploadedObj) {
            this.queryFormRmport.enclosureFileName = uploadedObj.fileName;
            this.queryFormRmport.enclosureFileUrl = uploadedObj.objectkey;
          }
        }
      });
    },
    changeRequest(file) {
      this.formList.append("file", file.file);
    },
    // 导入确定
    reliableRmport() {
      this.$refs['queryFormRmport'].validate((valid) => {
        if (valid) {
          this.$refs.uploadLead.submit();
          this.formList.append("educationTag", Number(this.$store.getters.getProjectId()));
          subjectCompetitionApi.englishListImportStudent(this.formList).then(res => {
            let isSuccess = (res.code == 200);
            this.$message({
                type: isSuccess ? "success":"error",
                message: res.msg
            });
            // this.$message.success(this.$t('studentsRegist.successfully'));
            this.formList = new FormData();
            this.fileList = [];
            this.listRmportVisible = false;
            this.queryFormRmport.enclosureFileName = '';
            this.queryForm.pageNum_ = 1;
            this.getListData();
          }).catch(() =>{
            this.formList = new FormData();
            this.fileList = [];
            this.queryFormRmport.enclosureFileName = '';
            // this.listRmportVisible = false;
          });
        }
      });
    },
    cancelClose() {},
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    reback() {
      this.$emit('change-exam-create-index')
    },
    getListData() {
      subjectCompetitionApi.englishListQuery(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        let list = [];
        if (this.dataList.length > 0) {
          this.taskMsg = this.dataList[0].taskMsg
          this.taskStatus = this.dataList[0].taskStatus
          this.dataList.forEach((el, index) => {
            if (el.zipUrl) {
              list.push(true) 
              this.zipUrlList = el.zipUrl
            } else {
              list.push(false) 
            }
          })
          if (list.includes(true)) {
            this.zipUrl = true
          } else {
            this.zipUrl = false
          }
        }
        
        this.queryForm.total_ = res.data.total_;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    loadDone(data, val) {
      this.loadList = data;
      this.loadList.forEach(el => {
        if (el.id === val) {
          // this.queryForm.condition.calendarName = el.fullName;
          // this.calendarName = el.fullName;
          this.useConfigParamList = val;
        }
      });
      // this.postInternshipSet(this.queryForm);
    },
    changeInput(val) {
      // this.loadList.forEach(el => {
      //   if (el.id === val) {
      //     this.queryForm.condition.calendarName = el.fullName;
      //   }
      // });
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    // 导入审核名单
    importAuditRosterClick() {
      // console.log('dfd',this.$refs.selectFile);
      // this.$refs.selectFile.click();
      
      this.listRmportVisible = true;
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        // let currentIds = [];
        // if (this.multipleSelection.length > 0) {
        //   this.multipleSelection.forEach((element) => {
        //     currentIds.push(element.id);
        //   });
        // }
        subjectCompetitionApi.postExportPicture({
          educationTag: Number(this.$store.getters.getProjectId())
          // "competitionId": this.examId.id,
          // "calendarId": this.queryForm.condition.calendarId,
          // "college": this.queryForm.condition.collegeName,
          // "studentIdOrName": this.queryForm.condition.studentIdOrName,
          // "status": this.queryForm.condition.status,
          // "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/competitionservice/competitionExport/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/competitionservice/competitionExport/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出
    exportAuditRoster() {
      if (this.zipUrl) {
      let path =`/api/competitionservice/cet/exportPicture?zipUrl=` + this.zipUrlList
         
        window.open(path)
        // subjectCompetitionApi.postExportPicture(this.zipUrlList).then(res => {
        //   this.$message.success(this.$t('studentsRegist.successfully'));
        // })
      }
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      // this.exportResult = null;
      // this.$refs.downloadRef.open();
      // this.exportButton = true;
      // this.cycleToGetKey();
    },
    // 下载模板
    exportTemplate() {
      subjectCompetitionApi.getPictureTemplate();
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    },
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC", 'X_PYLB', 'X_XWLX', 'X_XXXS', 'X_YX']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            trainingCategory: "X_PYLB",
            degreeType: "X_XWLX",
            formLearning: "X_XXXS",
            college: "X_YX",
            TrainingLevel: "X_PYCC"
          },
          res.data,
          this.options
        );
      });
    },
    reset() {
      // this.baseLevel = [];
      // Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '');
      this.queryForm.condition.college = '';
      this.queryForm.condition.status = '';
      // console.log(this.useConfigParamList, this.useConfigParam);
      
      this.queryForm.condition.calendarId = this.useConfigParamList;
      // this.useConfigParam = this.useConfigParamList;
      // this.queryForm.condition.calendarName = this.calendarName;
      // this.onSubmit();
      this.queryForm.pageNum_ = 1;
      this.getListData();
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-tempSet-export') {
              this.permitToExport = true;
            }
            if (item.authCode === 'graduateStu-tempSet-add') {
              this.permitToAdd = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style  scoped>
.color{
  color:#2f79ff
}
.colors{
  color: red
}
</style>
<style lang="scss" scoped>
  .student-regist-container ::v-deep {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
  }
</style>
